package com.ldj.tim.server.util;

import com.ldj.tim.common.constant.CacheConstants;
import com.ldj.tim.common.constant.MqConstants;
import com.ldj.tim.common.pojo.P2PInfo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author majinhui
 * @description
 * @create 2024/11/12 11:40
 **/
@Slf4j
@Component
public class RabbitMsgUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void retryMessage(Message message, P2PInfo info, Channel channel, String routingKey) throws IOException {
        //消费者重试
        Long retryCount = redisTemplate.opsForValue().increment(CacheConstants.RETRY_PREFIX + info.getMsgId());
        if (retryCount >= 5L) {
//            log.error("消息到达死信队列-->{}", message);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            rabbitTemplate.convertAndSend(MqConstants.DLX_EXCHANGE, routingKey, message);
            redisTemplate.delete(CacheConstants.RETRY_PREFIX + info.getMsgId());
        } else {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
